#!/bin/bash

INTERFACE="eth0"

save_rules() {
    echo "#!/usr/sbin/nft -f" > /etc/nftables.conf
    echo "flush ruleset" >> /etc/nftables.conf
    nft list ruleset >> /etc/nftables.conf
    chattr +i /etc/nftables.conf
}

block_inet_docker() {
    #                                       Rules (ip4v, ip6v)
    # ______________________________________________________________________________________________________#
    chattr -i /etc/nftables.conf
    nft flush ruleset
    nft add table inet filter

    # Default chain's policy
    nft add chain inet filter INPUT   { type filter hook input priority   0 \; policy drop \;}
    nft add chain inet filter FORWARD { type filter hook forward priority 0 \; policy drop \;}
    nft add chain inet filter OUTPUT  { type filter hook output priority  0 \; policy drop \;}


    # Chain INPUT
    nft add rule inet filter INPUT iif "lo" counter log prefix "Loopback"       accept # Accept "Loopback"
    nft add rule inet filter INPUT iif "docker0" ip saddr 172.17.0.0/16 counter log prefix \"[IN DOCKER]\" accept # DOCKER INPUT ACCEPT
    nft add rule inet filter INPUT iif "lo" ip6 daddr != ::1/128    counter log drop
    nft add rule inet filter INPUT iif "lo" ip saddr != 127.0.0.0/8 counter log drop
    nft add rule inet filter INPUT meta pkttype { broadcast, multicast }        drop   # DROP broadcast, multicast pkgs
    nft add rule inet filter INPUT ct state invalid                             drop   # DROP invalid pkg
    nft add rule inet filter INPUT iif "$INTERFACE" icmp type echo-reply        drop   # DROP ICMP type 0 (Echo Reply)
    nft add rule inet filter INPUT iif "$INTERFACE" icmp type echo-request      drop   # DROP ICMP type 8 (Echo Request)
    nft add rule inet filter INPUT counter drop


    # Chain FORWARD
    nft add rule inet filter FORWARD counter drop

    # TABLE NAT
    nft add table ip nat
    nft add chain ip nat prerouting { type nat hook prerouting priority 0 \; }
    nft add chain ip nat postrouting { type nat hook postrouting priority 100 \; }
    nft add rule ip nat postrouting ip saddr 172.17.0.0/16 oif "$INTERFACE" masquerade

    # Chain OUTPUT
    nft add rule inet filter OUTPUT oif "lo" counter                             accept # Accept "Loopback"
    nft add rule inet filter OUTPUT oif "docker0" ip saddr 172.17.0.0/16 counter log prefix \"[OUT DOCKER]\" accept # DOCKER OUTPUT ACCEPT
    nft add rule inet filter OUTPUT oif "lo" ip6 daddr != ::1/128    counter log drop
    nft add rule inet filter OUTPUT oif "lo" ip daddr != 127.0.0.0/8 counter log drop
    nft add rule inet filter OUTPUT meta pkttype { broadcast, multicast }        drop   # DROP broadcast, multicast pkgs
    nft add rule inet filter OUTPUT ct state invalid                             drop   # DROP invalid pkg
    nft add rule inet filter OUTPUT counter drop

}

block_inet_docker
save_rules
